<template>
  <div class="mobile-profile">
    <!-- 顶部个人信息 -->
    <div class="profile-header">
      <div class="avatar-wrapper">
        <div class="avatar">
          <van-image
            round
            width="72px"
            height="72px"
            src="https://img01.yzcdn.cn/vant/cat.jpeg"
          />
        </div>
        <div class="edit-avatar">
          <van-icon name="photograph" size="18" />
        </div>
      </div>
      <div class="user-info">
        <div class="user-name">张医生</div>
        <div class="user-role">财务部 - 主管</div>
        <div class="user-tags">
          <van-tag type="primary" size="medium">财务</van-tag>
          <van-tag type="success" size="medium">审批人</van-tag>
        </div>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-row">
      <div class="stats-item" @click="navigateTo('/profile/approvals')">
        <div class="stats-value">{{ stats.approvals }}</div>
        <div class="stats-label">待审批</div>
      </div>
      <div class="stats-item" @click="navigateTo('/profile/applications')">
        <div class="stats-value">{{ stats.applications }}</div>
        <div class="stats-label">申请中</div>
      </div>
      <div class="stats-item" @click="navigateTo('/asset/list')">
        <div class="stats-value">{{ stats.assets }}</div>
        <div class="stats-label">我的资产</div>
      </div>
    </div>

    <!-- 人事服务区 -->
    <div class="module-section">
      <div class="section-header">
        <div class="section-title">
          <van-icon name="user-circle-o" color="#1A7BB9" />
          <span>人事服务</span>
        </div>
      </div>
      <div class="grid-links">
        <div class="grid-item" @click="navigateTo('/profile/schedule')">
          <van-icon name="calendar-o" size="24" color="#1A7BB9" />
          <span>我的排班</span>
        </div>
        <div class="grid-item" @click="navigateTo('/profile/leave')">
          <van-icon name="underway-o" size="24" color="#4CB050" />
          <span>我的假期</span>
        </div>
        <div class="grid-item" @click="navigateTo('/profile/leave-apply')">
          <van-icon name="notes-o" size="24" color="#FF9800" />
          <span>离职申请</span>
        </div>
        <div class="grid-item" @click="navigateTo('/profile/transfer-apply')">
          <van-icon name="exchange" size="24" color="#8E24AA" />
          <span>调动申请</span>
        </div>
        <div class="grid-item" @click="navigateTo('/profile/attendance')">
          <van-icon name="clock-o" size="24" color="#2196F3" />
          <span>我的考勤</span>
        </div>
        <div class="grid-item" @click="navigateTo('/profile/certificate')">
          <van-icon name="award-o" size="24" color="#FFB300" />
          <span>证书管理</span>
        </div>
        <div class="grid-item" @click="navigateTo('/profile/contact')">
          <van-icon name="friends-o" size="24" color="#00BFAE" />
          <span>组织通讯录</span>
        </div>
      </div>
    </div>
    
    <!-- 我的任务 -->
    <div class="module-section">
      <div class="section-header">
        <div class="section-title">
          <van-icon name="todo-list-o" color="#1A7BB9" />
          <span>我的任务</span>
        </div>
        <div class="section-more" @click="navigateTo('/profile/todo')">查看全部</div>
      </div>
      
      <div class="task-list">
        <van-empty description="暂无待办任务" v-if="taskList.length === 0" />
        <van-cell-group v-else>
          <van-swipe-cell
            v-for="item in taskList"
            :key="item.id"
            :before-close="beforeCloseSwipe"
          >
            <van-cell clickable @click="viewTaskDetail(item)">
              <template #icon>
                <div class="task-icon" :class="item.priority">
                  <van-icon :name="getTaskIcon(item.type)" />
                </div>
              </template>
              <template #title>
                <div class="task-title">
                  {{ item.title }}
                </div>
              </template>
              <template #label>
                <div class="task-desc">
                  <span class="task-time">{{ item.deadline }}</span>
                  <van-tag :type="getTaskTagType(item.priority)" size="medium">{{ getTaskPriorityText(item.priority) }}</van-tag>
                </div>
              </template>
            </van-cell>
            <template #right>
              <van-button square type="primary" text="完成" class="swipe-btn" />
              <van-button square type="danger" text="删除" class="swipe-btn" />
            </template>
          </van-swipe-cell>
        </van-cell-group>
      </div>
    </div>
    
    <!-- 快捷入口 -->
    <div class="module-section">
      <div class="section-header">
        <div class="section-title">
          <van-icon name="fire-o" color="#1A7BB9" />
          <span>常用功能</span>
        </div>
      </div>
      
      <div class="grid-links">
        <div class="grid-item" @click="navigateTo('/finance/expense')">
          <van-icon name="balance-o" size="24" color="#1A7BB9" />
          <span>报销申请</span>
        </div>
        <div class="grid-item" @click="navigateTo('/profile/attendance')">
          <van-icon name="clock-o" size="24" color="#4CB050" />
          <span>考勤记录</span>
        </div>
        <div class="grid-item" @click="navigateTo('/profile/leave')">
          <van-icon name="calendar-o" size="24" color="#FF9800" />
          <span>请假申请</span>
        </div>
        <div class="grid-item" @click="navigateTo('/finance/salary')">
          <van-icon name="gold-coin-o" size="24" color="#8E24AA" />
          <span>工资查询</span>
        </div>
      </div>
    </div>
    
    <!-- 设置列表 -->
    <div class="module-section">
      <van-cell-group>
        <van-cell title="个人信息" icon="contact" is-link @click="navigateTo('/profile/info')" />
        <van-cell title="账号安全" icon="shield-o" is-link @click="navigateTo('/profile/security')" />
        <van-cell title="消息设置" icon="bell" is-link @click="navigateTo('/profile/notifications')" />
        <van-cell title="隐私设置" icon="eye-o" is-link @click="navigateTo('/profile/privacy')" />
        <van-cell title="帮助中心" icon="question-o" is-link @click="navigateTo('/profile/help')" />
        <van-cell title="关于我们" icon="info-o" is-link @click="navigateTo('/profile/about')" />
      </van-cell-group>
    </div>
    
    <!-- 退出登录 -->
    <div class="logout-btn">
      <van-button plain type="danger" block @click="logout">退出登录</van-button>
    </div>
    
    <!-- 底部导航栏 -->
    <van-tabbar v-model="activeTabbar" route>
      <van-tabbar-item name="home" icon="home-o" to="/new/home">首页</van-tabbar-item>
      <van-tabbar-item name="apps" icon="apps-o" to="/new/apps">应用</van-tabbar-item>
      <van-tabbar-item name="profile" icon="user-o" to="/new/profile">我的</van-tabbar-item>
    </van-tabbar>
    
    <!-- 任务详情弹出层 -->
    <van-popup
      v-model:show="showTaskDetail"
      round
      position="bottom"
      :style="{ height: '60%' }"
    >
      <div class="task-detail" v-if="currentTask">
        <div class="popup-header">
          <div class="popup-title">任务详情</div>
          <van-icon name="cross" size="20" @click="showTaskDetail = false" />
        </div>
        
        <div class="detail-content">
          <div class="detail-header">
            <div class="detail-title">{{ currentTask.title }}</div>
            <van-tag :type="getTaskTagType(currentTask.priority)" size="medium">
              {{ getTaskPriorityText(currentTask.priority) }}
            </van-tag>
          </div>
          
          <div class="detail-section">
            <div class="detail-label">截止时间</div>
            <div class="detail-value">{{ currentTask.deadline }}</div>
          </div>
          
          <div class="detail-section">
            <div class="detail-label">任务描述</div>
            <div class="detail-value">{{ currentTask.description }}</div>
          </div>
          
          <div class="detail-section">
            <div class="detail-label">创建时间</div>
            <div class="detail-value">{{ currentTask.createdAt }}</div>
          </div>
        </div>
        
        <div class="popup-footer">
          <van-button type="primary" block round @click="completeTask">完成任务</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { 
  Icon, Image as VanImage, Cell, CellGroup, Tag, SwipeCell,
  Button, Empty, Tabbar, TabbarItem, Popup, Dialog
} from 'vant'

export default {
  name: 'MobileProfile',
  components: {
    vanIcon: Icon,
    vanImage: VanImage,
    vanCell: Cell,
    vanCellGroup: CellGroup,
    vanTag: Tag,
    vanSwipeCell: SwipeCell,
    vanButton: Button,
    vanEmpty: Empty,
    vanTabbar: Tabbar,
    vanTabbarItem: TabbarItem,
    vanPopup: Popup
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    const activeTabbar = ref('profile')
    const showTaskDetail = ref(false)
    const currentTask = ref(null)
    
    // 获取用户信息
    const userInfo = computed(() => store.state.user.userInfo || {
      name: '张医生',
      position: '财务部 - 主管',
      avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg'
    })
    
    // 统计信息
    const stats = computed(() => ({
      approvals: store.state.todo.pendingCount || 5,
      applications: store.state.todo.submittedCount || 2,
      assets: store.state.asset.myAssetCount || 12
    }))
    
    // 任务列表 - 从store中获取或使用默认值
    const taskList = computed(() => {
      return store.state.mobile.messageCenter.todoList.length > 0 
        ? store.state.mobile.messageCenter.todoList
        : defaultTasks
    })
    
    // 默认任务数据
    const defaultTasks = reactive([
      {
        id: 1,
        title: '报销单审批',
        type: 'approval',
        priority: 'high',
        deadline: '今天 18:00',
        createdAt: '2024-05-20 09:30',
        description: '李护士提交的报销申请需要审批，金额为280.50元，关于办公用品采购。'
      },
      {
        id: 2,
        title: '部门预算填报',
        type: 'form',
        priority: 'medium',
        deadline: '明天 12:00',
        createdAt: '2024-05-19 16:45',
        description: '财务部6月份预算需要提交，截止日期为5月22日中午12点。'
      },
      {
        id: 3,
        title: '季度报表复核',
        type: 'review',
        priority: 'low',
        deadline: '5月30日',
        createdAt: '2024-05-18 10:15',
        description: '第二季度财务报表需要复核并提交至财务总监。'
      }
    ])
    
    // 获取任务图标
    const getTaskIcon = (type) => {
      switch(type) {
        case 'approval': return 'balance-o'
        case 'form': return 'records'
        case 'review': return 'document'
        default: return 'todo-list'
      }
    }
    
    // 获取任务标签类型
    const getTaskTagType = (priority) => {
      switch(priority) {
        case 'high': return 'danger'
        case 'medium': return 'warning'
        case 'low': return 'primary'
        default: return 'default'
      }
    }
    
    // 获取任务优先级文本
    const getTaskPriorityText = (priority) => {
      switch(priority) {
        case 'high': return '紧急'
        case 'medium': return '中等'
        case 'low': return '普通'
        default: return '普通'
      }
    }
    
    // 查看任务详情
    const viewTaskDetail = (task) => {
      currentTask.value = task
      showTaskDetail.value = true
    }
    
    // 处理滑动单元格关闭
    const beforeCloseSwipe = ({ position, instance }) => {
      switch (position) {
        case 'right':
          Dialog.confirm({
            title: '确认操作',
            message: '是否确认执行此操作？',
          }).then(() => {
            instance.close()
          }).catch(() => {
            instance.close()
          })
          return false
        default:
          return true
      }
    }
    
    // 完成任务
    const completeTask = () => {
      if (currentTask.value) {
        Dialog.alert({
          title: '操作成功',
          message: `已完成任务：${currentTask.value.title}`,
        }).then(() => {
          showTaskDetail.value = false
        })
      }
    }
    
    // 导航到指定路径
    const navigateTo = (path) => {
      router.push(path)
      
      // 记录访问历史
      store.dispatch('mobile/recordVisit', {
        path,
        name: path.split('/').pop(),
        icon: getIconForPath(path),
        iconBg: getColorForPath(path),
        time: new Date().toLocaleString('zh-CN', {
          month: 'numeric',
          day: 'numeric',
          hour: 'numeric',
          minute: 'numeric'
        })
      })
    }
    
    // 根据路径获取图标
    const getIconForPath = (path) => {
      if (path.includes('/finance')) return 'balance-o'
      if (path.includes('/material')) return 'shopping-cart-o'
      if (path.includes('/asset')) return 'desktop-o'
      if (path.includes('/profile')) return 'user-o'
      return 'apps-o'
    }
    
    // 根据路径获取颜色
    const getColorForPath = (path) => {
      if (path.includes('/finance')) return 'blue'
      if (path.includes('/material')) return 'green'
      if (path.includes('/asset')) return 'purple'
      if (path.includes('/profile')) return 'orange'
      return 'cyan'
    }
    
    // 退出登录
    const logout = () => {
      Dialog.confirm({
        title: '退出登录',
        message: '确定要退出登录吗？',
      }).then(() => {
        router.push('/login')
      })
    }
    
    onMounted(() => {
      // 加载待办任务
      store.dispatch('mobile/loadMessages')
    })
    
    return {
      activeTabbar,
      showTaskDetail,
      currentTask,
      userInfo,
      stats,
      taskList,
      getTaskIcon,
      getTaskTagType,
      getTaskPriorityText,
      viewTaskDetail,
      beforeCloseSwipe,
      completeTask,
      navigateTo,
      logout
    }
  }
}
</script>

<style scoped>
.mobile-profile {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 50px;
}

.profile-header {
  background-color: #1A7BB9;
  padding: 20px 16px;
  display: flex;
  align-items: center;
  color: white;
}

.avatar-wrapper {
  position: relative;
  margin-right: 16px;
}

.edit-avatar {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: #ffffff;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  color: #1A7BB9;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 4px;
}

.user-role {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.user-tags {
  display: flex;
  gap: 8px;
}

.stats-row {
  display: flex;
  margin: -24px 16px 16px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.stats-item {
  flex: 1;
  text-align: center;
  padding: 16px 0;
  position: relative;
}

.stats-item:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 25%;
  height: 50%;
  width: 1px;
  background-color: #f0f0f0;
}

.stats-value {
  font-size: 20px;
  font-weight: 600;
  color: #1A7BB9;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 12px;
  color: #666;
}

.module-section {
  margin: 0 16px 16px;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

.section-title .van-icon {
  margin-right: 4px;
}

.section-more {
  font-size: 14px;
  color: #1A7BB9;
}

.task-icon {
  width: 36px;
  height: 36px;
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  color: white;
}

.task-icon.high {
  background-color: #E53935;
}

.task-icon.medium {
  background-color: #FF9800;
}

.task-icon.low {
  background-color: #4CB050;
}

.task-title {
  font-size: 15px;
  font-weight: 500;
}

.task-desc {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 4px;
}

.task-time {
  font-size: 12px;
  color: #90A4AE;
}

.swipe-btn {
  height: 100%;
}

.grid-links {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  padding: 16px 0;
}

.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 12px;
  color: #333;
}

.logout-btn {
  margin: 20px 16px;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 16px;
  font-weight: 500;
}

.detail-content {
  padding: 16px;
  overflow-y: auto;
  max-height: calc(100% - 130px);
}

.detail-header {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.detail-title {
  font-size: 18px;
  font-weight: 600;
}

.detail-section {
  margin-bottom: 16px;
}

.detail-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.detail-value {
  font-size: 14px;
  color: #333;
}

.popup-footer {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}
</style>